// pages/mes/authentication/authentication.js
const sourceType = [
    ['camera'],
    ['album']
]
const sizeType = [
    ['compressed'],
    ['original']
]
const uploadFile = require('../../../lib/aliyun/uploadAliyun.js');
const app = getApp();
import Toast from '../../../component/toast/toast';
import utils from '../../../utils/util.js';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        beforeIndex: 2,
        afterIndex: 2,
        beforeIndexType: ['拍照', '相册'],
        idBefore: '../../../assets/image/identity_face.jpg',
        idAfter: '../../../assets/image/identitycard.jpg',
        idName: '',
        idNum: '',
        authChecked: false
    },
    beforeTypeChange(e) {
        console.log("beforeTypeChange" + e.detail.value);
        let value = e.detail.value;
        let taht = this;

    },
    afterTypeChange(e) {
        console.log("afterTypeChange" + e.detail.value);
    },
    clickBefore() {
        let that = this;
        wx.chooseImage({
            sizeType: sizeType[0],
            count: 1,
            success(res) {
                console.log(res.tempFilePaths[0]);
                that.setData({
                    idBefore: res.tempFilePaths[0]
                });
            }
        })
    },
    clickAfter() {
        let that = this;
        wx.chooseImage({
            sizeType: sizeType[0],
            count: 1,
            success(res) {
                console.log(res.tempFilePaths[0]);
                that.setData({
                    idAfter: res.tempFilePaths[0]
                });
            }
        })
    },
    uploadSyncImg(path, dir) {
        let promis = new Promise(function(resolve, reject) {
            uploadFile({
                filePath: path,
                dir: dir,
                success: function(res) {
                    resolve(res);
                },
                fail: function(res) {
                    reject(res);
                }
            });
        });
        return promis;
    },
    jointData(parmas) {
        let userInfo = app.userInfo;
        let date = utils.formatTime(new Date());
        let data = {};
        data.Id = '';
        data.UserInfoId = userInfo.Id;
        data.RealName = parmas.realName;
        data.IDNumber = parmas.idNum;
        data.FrontPhoto = parmas.beforeImg;
        data.BackPhoto = parmas.afterImg;
        data.HoldingPhoto = '';
        data.VerifyStatus = '1';
        data.VerifyTime = date;
        data.Reason = '';
        data.CreateDateTime = date;
        return data;
    },
    uploadInfoSerer(data) {
        let verifiedUrl = app.globalData.serverAddress.addUserVerified;
        let token = "Bearer " + app.globalData.token;
        wx.request({
            url: verifiedUrl,
            method: 'POST',
            data: data,
            header:{
                'content-type': 'application/json;chartset=utf-8', 
                'Authorization': token
            },
            success: function(res) {
                console.log("success" + JSON.stringify(res));
                if(res.statusCode == 200){
                    if (res.data.CodeStatus == 20000) {
                        app.userInfo.IsVerified = res.data.BodyContent.VerifyStatus;
                        Toast("上传成功！");
                        let parmas = JSON.stringify(res.data.BodyContent);
                        wx.redirectTo({
                            url: '/pages/mes/auth-result/auth-result?parmas=' + parmas,
                        })
                    }else{
                        Toast(res.data.Message); 
                    }
                }else{
                    Toast("上传失败，请重新提交！");
                }
            },
            fail: function(res) {
                console.log("fail" + JSON.stringify(res));
                Toast("上传失败，请重新提交！");
            },
            complete: function(res) {
                wx.hideToast();
            }
        })
    },
    commitAuth() {
        let name = this.data.idName;
        let cardNum = this.data.idNum;
        let beforeImg = this.data.idBefore;
        let afterImg = this.data.idAfter;
        let authChecked = this.data.authChecked;
        let dir = 'xianjian_wx_image';
        let that = this;
        let imgUrls = [];
        let cardId = utils.isCardID(cardNum);
        if (!name) {
            Toast("请填写真实姓名");
            return;
        }
        // if (typeof cardId == 'string') {
        //     Toast(cardId);
        //     return;
        // }
        if (!cardNum) {
            Toast("请填写身份证号码");
            return;
        } else if (cardNum.length != 18) {
            Toast("身份证号码输入有误");
            return;
        }
        if (beforeImg == '../../../assets/image/identity_face.jpg') {
            Toast("请选择上传身份证人像面");
            return;
        }
        if (afterImg == '../../../assets/image/identitycard.jpg') {
            Toast("请选择上传身份证国徽面");
            return;
        }
        if (!authChecked) {
            Toast("请阅读协议后再提交");
            return;
        }
        let parmas = {
            realName: name,
            idNum: cardNum,
            beforeImg: beforeImg,
            afterImg: afterImg
        };
        app.globalData.verifiedInfo = parmas;
        wx.showToast({
            title: '提交中...',
            icon: 'loading',
            duration: 1000000,
            mask: true
        });
        that.uploadSyncImg(beforeImg, dir).then(res => {
            if (res.statusCode == 200) {
                imgUrls.push(res.imgUrl);
            }
            console.log("update 1：" + JSON.stringify(res));
            return res.statusCode;
        }, err => {
            wx.hideToast();
            Toast("图片上传失败，请重新上传！");
            console.log("1" + JSON.stringify(err));
        }).then(statusCode => {
            if (statusCode == 200) {
                that.uploadSyncImg(afterImg, dir).then(res => {
                    if (res.statusCode == 200) {
                        imgUrls.push(res.imgUrl);
                    }
                    console.log("update 2：" + JSON.stringify(res));
                }, err => {
                    wx.hideToast();
                    Toast("图片上传失败，请重新上传！");
                    console.log("2" + JSON.stringify(err));
                }).then(() => {
                    console.log("图片上传完毕：" + imgUrls.length);
                    if (imgUrls.length == 2) {
                        parmas.beforeImg = imgUrls[0];
                        parmas.afterImg = imgUrls[1];
                        let data = that.jointData(parmas);
                        that.uploadInfoSerer(data);
                    }
                });
            }
        });
    },
    nameInput(event) {
        this.setData({
            idName: event.detail.value
        });
    },
    cardNumInput(event) {
        this.setData({
            idNum: event.detail.value
        });
    },
    checkboxChange(e) {
        let currentCheck = this.data.authChecked;
        this.setData({
            authChecked: !currentCheck
        });
    },
    toAgreement(){
        app.globalData.globalWebUrl = app.globalData.agreementUrl;
        wx.navigateTo({
            url: '/pages/agreement-web/agreement-web?title=闲将信息发布规范'
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})